package pl.edu.agh.neuraleconomy.core.experiment.statistics;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;

import pl.edu.agh.neuraleconomy.common.utils.FileUtils;
import pl.edu.agh.neuraleconomy.core.simulation.SimulationEngine;
import pl.edu.agh.neuraleconomy.core.simulation.Transaction;
import pl.edu.agh.neuraleconomy.core.ta.advice.Advice;

public abstract class SaveToFileStatistic implements IStatistic {
	private File file = null;
	private FileWriter fw = null;
	private BufferedWriter writer = null;

	public SaveToFileStatistic(File dir, String fileName) {
		try {
			file = File.createTempFile(fileName, ".txt", dir);
			fw = new FileWriter(file);
			writer = new BufferedWriter(fw);
		} catch (IOException e) {
			makeClean(true);
		}
	}

	public void iteration(Date date, SimulationEngine simulation, List<Advice> advices, List<Transaction> transactionsMade) {
		if (writer != null) {
			try {
				String iterationString = iterationString(date, simulation, advices, transactionsMade);
				if (!iterationString.trim().isEmpty()) {
					writer.append(iterationString);
					writer.append("\n");
					writer.flush();
				}
			} catch (IOException e) {
				makeClean(true);
			}
		}
	}

	public void finalizeStatistic() {
		makeClean(false);
	}

	protected abstract String iterationString(Date date, SimulationEngine simulation, List<Advice> advices,
			List<Transaction> transactionsMade);

	private void makeClean(boolean deleteFile) {
		IOUtils.closeQuietly(writer);
		IOUtils.closeQuietly(fw);
		if (deleteFile) {
			FileUtils.deleteQuietly(file);
		}
		file = null;
		fw = null;
		writer = null;
	}

}
